package com.yiwei.zxp.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.IdcardAuthBean;
import com.yiwei.zxp.api.bean.UploadImgBean;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.Const;
import com.yiwei.zxp.constant.IdCardBitmap;
import com.yiwei.zxp.fragment.HasLicenseIdentityFragment;
import com.yiwei.zxp.fragment.WithoutLicenseIdentityFragment;
import com.yiwei.zxp.util.ImageUtil;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.view.HomeViewPager;
import com.yiwei.zxp.view.V19FrameLayout;
import com.yiwei.zxp.view.uploadImage.UploadImgAdapter;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class QualificationIdentityActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.btn_license_has)
    SuperButton btnLicenseHas;
    @BindView(R.id.btn_license_without)
    SuperButton btnLicenseWithout;
    @BindView(R.id.pager)
    HomeViewPager pager;
    private Unbinder unbiner;
    private int takeType;
    private static final String DEFAULT_NAME1 = "front_image.jpg";
    private static final String DEFAULT_NAME2 = "back_image.jpg";
    private HasLicenseIdentityFragment hasFragment;
    private WithoutLicenseIdentityFragment noFragment;
    private UploadImgAdapter uploadImgAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qualification_identity);
        initWebViewBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("资质认证");
        txtRight.setVisibility(View.VISIBLE);
        txtRight.setText("确认上传");
        hasFragment = new HasLicenseIdentityFragment();
        noFragment = new WithoutLicenseIdentityFragment();


        String type = getIntent().getStringExtra("type");
        if (!TextUtils.isEmpty(type)) {
            if (type.equals("1")) {
                Bundle bundle = new Bundle();
                bundle.putString(Const.SettingShopData.License.licence_name, getIntent().getStringExtra(Const.SettingShopData.License.licence_name));
                bundle.putString(Const.SettingShopData.License.idcard_front_img, getIntent().getStringExtra(Const.SettingShopData.License.idcard_front_img));
                bundle.putString(Const.SettingShopData.License.idcard_no, getIntent().getStringExtra(Const.SettingShopData.License.idcard_no));
                bundle.putString(Const.SettingShopData.License.licence_img, getIntent().getStringExtra(Const.SettingShopData.License.licence_img));
                bundle.putString(Const.SettingShopData.License.licence_no, getIntent().getStringExtra(Const.SettingShopData.License.licence_no));
                bundle.putString(Const.SettingShopData.License.realname, getIntent().getStringExtra(Const.SettingShopData.License.realname));
                hasFragment.setArguments(bundle);
            } else if (type.equals("2")) {
                pager.setCurrentItem(1);
                Bundle bundle = new Bundle();
                bundle.putString(Const.SettingShopData.Idcard.idcard_front_img, getIntent().getStringExtra(Const.SettingShopData.Idcard.idcard_front_img));
                bundle.putString(Const.SettingShopData.Idcard.idcard_no, getIntent().getStringExtra(Const.SettingShopData.Idcard.idcard_no));
                bundle.putString(Const.SettingShopData.Idcard.realname, getIntent().getStringExtra(Const.SettingShopData.Idcard.realname));
                bundle.putString(Const.SettingShopData.Idcard.idcard_back_img, getIntent().getStringExtra(Const.SettingShopData.Idcard.idcard_back_img));
                bundle.putString(Const.SettingShopData.Idcard.idcard_hand_img, getIntent().getStringExtra(Const.SettingShopData.Idcard.idcard_hand_img));

                noFragment.setArguments(bundle);

            }
        }

        Fragment[] fragments = new Fragment[]{hasFragment, noFragment};
        pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public Fragment getItem(int position) {
                return fragments[position];
            }

            @Override
            public int getCount() {
                return fragments.length;
            }
        });
    }

    public void startTakePhoto(int type) {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                takeType = type;
                if (type == 1) {
                    startActivity(DEFAULT_NAME1);
                }
                if (type == 2) {
                    startActivity(DEFAULT_NAME2);
                } else if (type == 3) {
                    goToTakePhoto();
                } else if (type == 4) {
                    goToTakePhoto();
                }
            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }


    private void startActivity(String paramString) {
        Intent localIntent = new Intent(this, CameraActivity.class);
        localIntent.putExtra("path", "/sdcard/pictures");
        localIntent.putExtra("name", paramString);
        localIntent.putExtra("type", "idcard");
        startActivityForResult(localIntent, 100);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == -1) {
                try {
                    if (takeType == 1) {
                        if (IdCardBitmap.bitmap != null) {
                            getUploadImg(IdCardBitmap.bitmap);
                        }
                    } else if (takeType == 2) {
                        if (IdCardBitmap.bitmap != null) {
                            getUploadImg(IdCardBitmap.bitmap);

                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            if (uploadImgAdapter != null) {
                uploadImgAdapter.onActivityResult(requestCode, resultCode, data);
            }
        }

    }

    private void goToTakePhoto() {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                if (uploadImgAdapter == null) {
                    initUploadImgAdapter();
                }
                uploadImgAdapter.withMode(UploadImgAdapter.MODE_IMG).showDialog();
            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    private void initUploadImgAdapter() {
        uploadImgAdapter = new UploadImgAdapter(this, new UploadImgAdapter.Action2() {
            @Override
            public void call(Bitmap file, int mode) {
                if (mode == UploadImgAdapter.MODE_IMG) {
                    getUploadImg(file);
                }
            }

            @Override
            public void callTake(File file, int mode) {
                if (mode == UploadImgAdapter.MODE_IMG) {
                    getUploadImg(ImageUtil.decodeUri(QualificationIdentityActivity.this, Uri.parse(file.getAbsolutePath())));
                }
            }
        }, 1);
    }

    public void getUploadImg(Bitmap bitmap) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        UploadImgBean bean = new UploadImgBean();
        bean.img = ImageUtil.Bitmap2StrByBase64(bitmap, 100);
        Api.api_service.getUploadImg(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    loadingDialog.dismiss();
                    if (takeType == 1) {
                        getIdcardAuth(result.datas.url, "0");
//                        if (pager.getCurrentItem() == 0) {
//                            getIdcardAuth(result.datas.url,"0");
//                            hasFragment.setIdcardImg(result.datas.url);
//                        } else {
//                            noFragment.setIdcardImg(result.datas.url);
//                        }
                    } else if (takeType == 2) {
                        getIdcardAuth(result.datas.url, "1");
//                        noFragment.setIdcardBackImg(result.datas.url);
                    } else if (takeType == 3) {
                        hasFragment.setLicenseImg(result.datas.url);
                    } else if (takeType == 4) {
                        noFragment.setHandIdcard(result.datas.url);
                    }
                });
    }

    public void getIdcardAuth(String imgUrl, String side) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        IdcardAuthBean bean = new IdcardAuthBean();
        bean.img = imgUrl;
        bean.side = side;
        Api.api_service.getIdcardAuth(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (pager.getCurrentItem() == 0) {
                        hasFragment.setIdcardImg(result.datas.front_image, result.datas.idno, result.datas.name);
                    } else {
                        if (side.equals("0")) {
                            noFragment.setIdcardImg(result.datas.front_image, result.datas.idno, result.datas.name);
                        } else {
                            noFragment.setIdcardBackImg(result.datas.back_image);
                        }

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        pager.removeAllViews();
        if (IdCardBitmap.bitmap != null) {
            IdCardBitmap.bitmap.recycle();
            IdCardBitmap.bitmap = null;
        }

        EventBus.getDefault().unregister(this);
        unbiner.unbind();
        unbiner = null;

    }

    private void setPageChange(int poi) {
        if (poi == 0) {
            btnLicenseHas.setShapeSolidColor(0xffFF0030).setUseShape();
            btnLicenseHas.setTextColor(0xffffffff);

            btnLicenseWithout.setShapeSolidColor(0xffffffff).setUseShape();
            btnLicenseWithout.setTextColor(0xff010101);
            btnLicenseWithout.setText("无营业执照");
        } else {
            btnLicenseWithout.setShapeSolidColor(0xffFF0030).setUseShape();
            btnLicenseWithout.setTextColor(0xffffffff);
            btnLicenseWithout.setText("身份证认证");
            btnLicenseHas.setShapeSolidColor(0xffffffff).setUseShape();
            btnLicenseHas.setTextColor(0xff010101);

        }
        pager.setCurrentItem(poi);
    }


    @OnClick({R.id.btn_back, R.id.txt_right, R.id.btn_license_has, R.id.btn_license_without})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.txt_right:
                if (pager.getCurrentItem() == 0) {
                    hasFragment.showSubmitDialog();
                } else {
                    noFragment.showSubmitDialog();
                }
                break;
            case R.id.btn_license_has:
                setPageChange(0);
                break;
            case R.id.btn_license_without:
                setPageChange(1);
                break;
        }
    }
}
